﻿using UnityEngine;
using System.Collections;
using Holoville.HOTween;

public partial class MainScene : Scene
{
	const float POST_CLICK_DELAY = 0.5f;

	UIPanel topLeftPanel;
	UIPanel topRightPanel;
	UIPanel leftPanel;
	UIPanel rightPanel;
	UIPanel centerPanel;
	CameraPathBezierAnimator firstMoveAnimator;

	public GameObject[] quickPvpGaugeArray;

	public Badge mailBadge;
	public Badge friendBadge;

	public GameObject fadePanel;
	public FadeScreen fadeScreen;

	public AnimatedAlpha achievementAlpha;
	public AnimatedAlpha friendAlpha;
	public AnimatedAlpha shopAlpha;
	public AnimatedAlpha questAlpha;		
	public AnimatedAlpha challengeAlpha;
	public AnimatedAlpha bossAlpha;
	public AnimatedAlpha dundeonAlpha;
	public AnimatedAlpha worldAlpha;

	public GameObject questGoingMarkObject;
	public GameObject questCompleteMarkObject;
    public GameObject questGoingMarkIconObject;
    public GameObject questCompleteMarkIconObject;

    public GameObject[] MenuList;

    public GameObject achievemnetNewMarkObject;

	public override void AwakeScene ()
	{
		// 배경 애니메이션 포함된 씬 추가 로드
		if ( Application.isLoadingLevel )
			Application.LoadLevelAdditive("Main_Background");

		ResetVariables();
		InitGameObject();

		Popup_Blur.ClearAll();

		topRightPanel = GameObject.Find ("Panel - TopRight").GetComponent<UIPanel>();
		leftPanel = GameObject.Find ("Panel - BottomLeft").GetComponent<UIPanel>();
		rightPanel = GameObject.Find ("Panel - BottomRight").GetComponent<UIPanel>();
		centerPanel = GameObject.Find ("Panel - Center").GetComponent<UIPanel>();

		hasLeftTopMenu = true;

		// UserModel 갱신에 종속된 데이터 업데이트
		RefreshDataByUserModel();

		// 임시 치트 버튼 리스너 등록
		// AddTempButtonListener();

		//choice member clear
		ResourceManager.Inst.ClearAllChoiceModel();
    }

	public override void PostAwakeScene ()
	{
		InitAnimatedAlpha();
	}

	public override void StartScene ()
	{
        if (UserData.Instance.userModel.achiCompleteCount != 0)
            achievemnetNewMarkObject.SetActive(true);
		// First Time
		if (UserData.Instance.isFirstTimeMainScene == true)
		{
			StartCoroutine("TweenPanelProcess");
			StartCoroutine("CameraMoveProcess");		

			UserData.Instance.isFirstTimeMainScene = false; // 위치 변경하면 안되는 코드
			return;
		}

		StartCoroutine( LevelUpCoroutine() );

        QuestManager.instance.CheckAndStartQuest();

        if (UserData.Instance.isOpenNewBossAreaForGStar)
        {
            if(UserData.Instance.userModel.regions.regionMap_Dic.Count == 4)
            {
                Popup_GameClear popup = PopupManager.PushPopup(PopupKind.GameClear) as Popup_GameClear;
                SoundController.PlaySound("UI_clear_game");
            }
            else
            {
                Popup_BossClear popup = PopupManager.PushPopup(PopupKind.BossClear) as Popup_BossClear;
                DGStarBossList info = GameData.Inst.GetGStarBossListByRegionId(WorldSceneManager_GStar.sentResearchAreaId);
                popup.bodyLabel1.text = TextController.GetStringWithId("GstarBossRaidWinText1").Replace("{0}", TextController.GetStringWithId(string.Format("bossName{0}", info.bossID)));
                popup.bodyLabel2.text = TextController.GetStringWithId("GstarBossRaidWinText2");
                SoundController.PlaySound("UI_clear_boss");
            }

            UserData.Instance.isOpenNewBossAreaForGStar = false;
        }
    }

    public void GotoLoadingScene()
    {
        SceneController.LoadLevel("LoadingScene");
    }

	IEnumerator LevelUpCoroutine()
	{
		yield return new WaitForSeconds(1.0f);
		ToastUtility.LevelUpToast();
	}

	void AddTempButtonListener()
	{
		//TODO:TEMP-CHEAT-BOSS
		GameObject.Find("TEMP_CHEAT_BOSS_10001").GetComponent<UIButton>().onClick.Add(new EventDelegate(() => {
			Debug.Log("TEMP_CHEAT_BOSS_10001");
			NetworkManager.Instance.C2S_CHEAT_BOSS("/cheat/addBoss", 100, (receiveData) =>
			                                       {
				//TODO:TEMP-order point reset
				Popup_OneButton sc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
				sc.SetPopupWithTitleAndBody("실행", (receiveData.ecode == 0) ? "했습니다!" : "못했습니다!");
				//sc.SetEventOK(gameObject, "OnClick_Order_Proc");
			});
		}));
		GameObject.Find("TEMP_CHEAT_BOSS_10002").GetComponent<UIButton>().onClick.Add(new EventDelegate(() =>
		                                                                                                {
			Debug.Log("TEMP_CHEAT_BOSS_10002");
			NetworkManager.Instance.C2S_CHEAT_BOSS("/cheat/addBoss", 101, (receiveData) =>
			                                       {
				//TODO:TEMP-order point reset
				Popup_OneButton sc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
				sc.SetPopupWithTitleAndBody("실행", (receiveData.ecode == 0) ? "했습니다!" : "못했습니다!");
				//sc.SetEventOK(gameObject, "OnClick_Order_Proc");
			});
		}));
		GameObject.Find( "TEMP_CHEAT_FPS" ).GetComponent<UIButton>().onClick.Add( new EventDelegate( () =>
		{
			Debug.Log( "TEMP_CHEAT_FPS" );
			Scene.ToggleDiagnostic();
		} ) );
	}

	void RefreshBadge()
	{
		int newFriendBadgeCount = (int)(UserData.Instance.userModel.newAlarmCount & 1023);
		int requestFriendBadgeCount = (int)(UserData.Instance.userModel.newAlarmCount >> 10 & 1023);
		int mailMessageBadgeCount = (int)(UserData.Instance.userModel.newAlarmCount >> 20 & 1023);
		int battleMessageBadgeCount = (int)(UserData.Instance.userModel.newAlarmCount >> 30 & 1023);
		int rewardMessageBadgeCount = (int)(UserData.Instance.userModel.newAlarmCount >> 40 & 1023);
		
		EPLog.Log ("(친구)새로운 친구 : " + newFriendBadgeCount);
		EPLog.Log ("(친구)친구 신청 : " + requestFriendBadgeCount);
		EPLog.Log ("(메세지)쪽지 : " + mailMessageBadgeCount);
		EPLog.Log ("(메세지)전투 : " + battleMessageBadgeCount);
		EPLog.Log ("(메시지)보상 : " + rewardMessageBadgeCount);
		
		if (newFriendBadgeCount + requestFriendBadgeCount > 0)
		{
			friendBadge.badgeCount = newFriendBadgeCount + requestFriendBadgeCount;
			NGUITools.SetActive(friendBadge.gameObject, true);
		}
		
		if (mailMessageBadgeCount + battleMessageBadgeCount + rewardMessageBadgeCount > 0)
		{
			mailBadge.badgeCount = mailMessageBadgeCount + battleMessageBadgeCount + rewardMessageBadgeCount;
			NGUITools.SetActive(mailBadge.gameObject, true);
		}
	}

	// UserModel 변경시 갱신 되는 데이터 처리
	void RefreshDataByUserModel()
	{
		Debug.Log (SceneController.CrrScene + "(RefreshDataByUserModel)");
		NetworkManager.Instance.C2S_LEGION_GET((responseData) => {

			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopup(responseData.ecode);
				return;
			}

			UserData.Instance.userModel = responseData.data;

			// 일일 침략 게이지 갱신
			if (UserData.Instance.userModel.quickPvpInfo != null)
				SetInvasionGause(UserData.Instance.userModel.quickPvpInfo.victoryCount);

			// 메일 뱃지 확인
			if (UserData.Instance.userModel.newAlarmCount > 0)
				RefreshBadge();

			//For QuestStateMark
            if (UserData.Instance.userModel.questInfo.state == 2 || UserData.Instance.userModel.questInfo.state == 3 )
			{
				questGoingMarkObject.SetActive(true);
				questCompleteMarkObject.SetActive(false);
                if (PlayerPrefs.GetInt("questVisit") == 0)
                    questGoingMarkIconObject.SetActive(true);

                DQuestInfo questInfo = GameData.Inst.GetQuestInfo(UserData.Instance.userModel.questInfo.questId);

                GameObject obj = Resources.Load("Prefab/UI/touch") as GameObject;
                GameObject questMarker = Instantiate(obj) as GameObject;

                switch (questInfo.objective)
                {
                    case 1:
                    case 2:
                    case 11:
                    case 21:
                        questMarker.transform.parent = MenuList[(int)MainSceneMenu.CharacterInfo].transform;
                        break;
                    case 31:
                    case 32:
                    case 33:
                    case 34:
                    case 35:
                    case 36:
                        questMarker.transform.parent = MenuList[(int)MainSceneMenu.World].transform;
                        break;
                    case 41:
                    case 42:
                        questMarker.transform.parent = MenuList[(int)MainSceneMenu.QuickPVP].transform;
                        break;
                    case 51:
                    case 52:
                        questMarker.transform.parent = MenuList[(int)MainSceneMenu.BossList].transform;
                        break;
                    case 61:
                        questMarker.transform.parent = MenuList[(int)MainSceneMenu.Achievement].transform;
                        break;
                    case 71:
                    case 72:
                        questMarker.transform.parent = MenuList[(int)MainSceneMenu.Friend].transform;
                        break;
                    case 81:
                        questMarker.transform.parent = MenuList[(int)MainSceneMenu.Store].transform;
                        break;
                }

                questMarker.transform.localPosition = Vector3.zero;
                questMarker.transform.localScale = Vector3.one;
			}
			else if( UserData.Instance.userModel.questInfo.state == 4 )
			{
				questGoingMarkObject.SetActive(false);
				questCompleteMarkObject.SetActive(true);
                questCompleteMarkIconObject.SetActive(true);
			}      
		});
	}

	#region - GStar Version
	void ResetGame()
	{
		SceneController.LoadLevel("login");
	}
	#endregion

	public void SetInvasionGause(int quickPvpVictoryCount)
	{
		for (int i = 0; i < quickPvpGaugeArray.Length; i++)
			NGUITools.SetActive(quickPvpGaugeArray[i], false);
		
		for (int i = 0; i < quickPvpVictoryCount; i++)
			NGUITools.SetActive(quickPvpGaugeArray[i], true);
	}

	// 메인씬에 진입시에 초기화 하는 변수들
	void ResetVariables()
	{
		UserData.Instance.raidBossId = 0;
		UserData.Instance.raidBossModel = null;
		UserData.Instance.isQuickPVPBattle = false;
		UserData.Instance.quickPVPUserModel = null;
		UserData.Instance.battleFriend = null;
		UserData.Instance.battleFriendUserModel = null;
		UserData.Instance.battleFriendId = 0;
		UserData.Instance.battleFriendIsMyFriend = false;
		UserData.Instance.counterAttackMsgId = 0;
	}

	// 메인씬 진입시 게임오브젝트 활성화/비활성화 하는 것들
	void InitGameObject()
	{
		NGUITools.SetActive(mailBadge.gameObject, false);
		NGUITools.SetActive(friendBadge.gameObject, false);
	}

	// 메인씬 처음 진입시 재생하는 애니메이션을 위한 알파값 초기화
	void InitAnimatedAlpha()
	{
		GameObject UIRoot = GameObject.Find ("UI Root");
		topLeftPanel = SceneController.m_TopLeftMenu.GetComponent<UIPanel>();
		topLeftPanel.GetComponent<AnimatedAlpha>().alpha = 0.0f;

		if (UserData.Instance.isFirstTimeMainScene == true)
		{
			topLeftPanel.GetComponent<AnimatedAlpha>().alpha = 0.0f;
			topRightPanel.GetComponent<AnimatedAlpha>().alpha = 0.0f;
			centerPanel.GetComponent<AnimatedAlpha>().alpha = 0.0f;
			
			achievementAlpha.alpha = 0.0f;
			friendAlpha.alpha = 0.0f;
			shopAlpha.alpha = 0.0f;
			questAlpha.alpha = 0.0f;
			
			challengeAlpha.alpha = 0.0f;
			bossAlpha.alpha = 0.0f;
			dundeonAlpha.alpha = 0.0f;
			worldAlpha.alpha = 0.0f;
		}
		else
		{
			topLeftPanel.GetComponent<AnimatedAlpha>().alpha = 1.0f;
			topRightPanel.GetComponent<AnimatedAlpha>().alpha = 1.0f;
			centerPanel.GetComponent<AnimatedAlpha>().alpha = 1.0f;
			
			achievementAlpha.alpha = 1.0f;
			friendAlpha.alpha = 1.0f;
			shopAlpha.alpha = 1.0f;
			questAlpha.alpha = 1.0f;
			
			challengeAlpha.alpha = 1.0f;
			bossAlpha.alpha = 1.0f;
			dundeonAlpha.alpha = 1.0f;
			worldAlpha.alpha = 1.0f;
		}
	}

	IEnumerator CameraMoveProcess()
	{
		firstMoveAnimator = GameObject.Find ("Camera Path_first").GetComponent<CameraPathBezierAnimator>();
		firstMoveAnimator.Play();
		yield return null;
	}

	IEnumerator TweenPanelProcess()
	{
		if (centerPanel == null || topLeftPanel == null || topRightPanel == null || leftPanel == null || rightPanel == null)
			yield break;

		HOTween.To (centerPanel, 1.0f, new TweenParms()
		            .Prop("alpha", 1.0f)
		            .Delay(uiStartCenterPanelDelay)
		            .Ease(EaseType.EaseInOutCubic)
		            );

		yield return new WaitForSeconds(uiStartOtherPanelDelay);

		GameObject.Find ("UI Root").animation.Play();
        QuestManager.instance.CheckAndStartQuest();

		yield return null;
	}

	void HidePanel()
	{
		HOTween.To (topLeftPanel.GetComponent<AnimatedAlpha>(), 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		HOTween.To (topRightPanel.GetComponent<AnimatedAlpha>(), 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		HOTween.To (centerPanel.GetComponent<AnimatedAlpha>(), 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));

		HOTween.To (achievementAlpha, 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		HOTween.To (friendAlpha, 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		HOTween.To (shopAlpha, 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		HOTween.To (questAlpha, 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		
		HOTween.To (challengeAlpha, 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		HOTween.To (bossAlpha, 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		HOTween.To (dundeonAlpha, 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
		HOTween.To (worldAlpha, 0.4f, new TweenParms().Prop("alpha", 0.0f).Ease(EaseType.EaseInOutCubic));
	}


    public override void HelpButton()
    {
        Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
        pt.SetPopupWithTutorialKind(TutorialKind.helpMainInfoA);
        pt.SetEventOK(gameObject, "OnFirstHelp");
        pt.SetEventNO(gameObject, "OnFirstHelp");
    }

    void OnFirstHelp()
    {
        Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
        pt.SetPopupWithTutorialKind(TutorialKind.helpMainInfoB);
    }
}
